﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ortodoctor.gridComponent;
using System.Data;
using Ortodoctor.modelo;
using Ortodoctor.Componentes;

namespace Ortodoctor.Funcionario
{
    public partial class CadastroCliente : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["USUARIO"] == null)
                Response.Redirect("Login.aspx");

            modeloCliente model = new modeloCliente();
            Grid grid = new Grid(model.getAllClient(), "id_cliente");
            Session["GRID_CLINTE"] = grid;

            modeloCliente modelo = new modeloCliente();
            DataTable dt = modelo.getAll();

            dt.DefaultView.Sort = "[nome] ASC";
            dt = dt.DefaultView.ToTable();
            string options = "";
            options += string.Format("<option value='{0}' >{1}</option>", "-1", "Nenhum");
            foreach (DataRow dr in dt.Rows)
            {
                options += string.Format("<option value='{0}' >{1}</option>", dr["id_cliente"].ToString(), dr["nome"].ToString());
            }
            options = "<select id='selectID' style='width: 100%'>" + options + "</select>";
            string selectClient = "$('#selectID').replaceWith($(\"" + options + "\"));";
            ModeloClinica mod = new ModeloClinica();
            DataTable clin = mod.getAll();

            foreach (DataRow dr in clin.Rows)
            {
                clinica.Items.Add(new ListItem(dr["cidade"].ToString(),dr["id_clinica"].ToString()));
            }

            scripts.InnerHtml = "<script> " + selectClient + "</script>";
        }

        [WebMethod]
        public static string getDados(string page, string rp, string sortname, string sortorder, string query, string qtype)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINTE"]);
            grid.page = Convert.ToInt32(page);
            DataTable dt = grid.dados.Clone();

            if (string.IsNullOrEmpty(query))
            {
                int numeroItensPagina = Convert.ToInt32(rp);
                int numeroPagina = Convert.ToInt32(page);
                int inicio = numeroItensPagina * (numeroPagina - 1);

                for (int i = inicio; i < inicio + numeroItensPagina && i < grid.dados.Rows.Count; ++i)
                {
                    DataRow dr = dt.NewRow();
                    foreach (DataColumn dc in dt.Columns)
                        dr[dc.ColumnName] = grid.dados.Rows[i][dc.ColumnName];

                    dt.Rows.Add(dr);
                }
                if (dt.Rows.Count > 0)
                {
                    dt.DefaultView.Sort = sortname + " " + sortorder;
                    dt = dt.DefaultView.ToTable();
                }
            }
            else
            {
                dt = grid.dados.Copy();
                dt.DefaultView.RowFilter = string.Format("[{0}] LIKE '%{1}%'", qtype, query);
                dt = dt.DefaultView.ToTable();
            }
            return grid.getDadosToJson(dt);
        }

        [WebMethod]
        public static string addToTable(string dados)
        {
            
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINTE"]);

            modeloEndereco endereco = new modeloEndereco();
            string[] strEnd = dados.Split('#')[1].Split('|');
            string[] strCliente = dados.Split('#')[0].Split('|');
            int p=0;
            try
            {
                p = Convert.ToInt32(strEnd[1]);
            }
            catch (Exception e) { p = 0; }
            modeloCliente cli = new modeloCliente();
            if (!cli.checkClient(strCliente[0],strCliente[1]))
            {
                Endereco end = new Endereco(-1,
                                             strEnd[0].ToString(),
                                             p,
                                             strEnd[3].ToString(),
                                             strEnd[2].ToString(),
                                             strEnd[4].ToString(),
                                             strEnd[5].ToString());
                int id = endereco.insert(end);
                end.IdEndereco = id;
                modeloCliente client = new modeloCliente();
                DateTime p1 = new DateTime();
                try
                {
                    p1 = Convert.ToDateTime(strCliente[3]);
                }
                catch (Exception e) {  }

                Cliente cliente = new Cliente(-1,
                                              end,
                                              strCliente[0],
                                              p1,
                                              DateTime.Now,
                                              strCliente[1],
                                              strCliente[2],
                                              strCliente[4],
                                              strCliente[5],
                                              strCliente[6],
                                              Convert.ToInt32(strCliente[8]));
                int id_cliente = client.insert(cliente);
                DataRow dr = grid.dados.NewRow();
                dr["id_cliente"] = id_cliente.ToString();
                dr["nome"] = cliente.Nome;
                dr["telefone1"] = cliente.Telefone1;
                dr["telefone2"] = cliente.Telefone2;
                dr["email"] = cliente.Email;

                grid.dados.Rows.Add(dr);

                if (!strCliente[7].Equals("-1"))
                {
                    modeloIndicado modInd = new modeloIndicado();
                    modInd.insert(new Indicado(-1,
                                               id_cliente,
                                               Convert.ToInt32(strCliente[7])));
                }

                grid.total++;
                HttpContext.Current.Session["GRID_CLINTE"] = grid;
                return "<option value='" + id_cliente + "'>" + strCliente[0] + "</option>";
            }
            else
            {
                return "CPF";
            }
        }

        [WebMethod]
        public static string editTable(int id, string dados)
        {
            
            //Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINTE"]);
            //grid.editTable(id, dados.Split('|'));
            //HttpContext.Current.Session["GRID_CLINTE"] = grid;
            //return "editou";

            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINTE"]);

            string[] strEnd = dados.Split('#')[1].Split('|');
            string[] strCliente = dados.Split('#')[0].Split('|');

            int p1 = 0; int p3 = 0;
            try
            {
                p1 = Convert.ToInt32(HttpContext.Current.Session["ENDERECO_CLIENT"]);
            }
            catch (Exception e) { p1 = 0; }
            //
            try
            {
                p3 = Convert.ToInt32(strEnd[1]);
            }
            catch (Exception e) { p3 = 0; }

            modeloEndereco endereco = new modeloEndereco(); 
            Endereco end = new Endereco(p1, 
                                         strEnd[0].ToString(), 
                                         p3, 
                                         strEnd[3].ToString(), 
                                         strEnd[2].ToString(), 
                                         strEnd[4].ToString(),
                                         strEnd[5].ToString());
            endereco.update(end);

            modeloCliente client = new modeloCliente();
            DateTime dt = new DateTime();
            try
            {
                dt = Convert.ToDateTime(strCliente[3]);
            }
            catch (Exception e) { }

            Cliente cliente = new Cliente(id,
                                          end,
                                          strCliente[0],
                                          dt,
                                          DateTime.Now,
                                          strCliente[1],
                                          strCliente[2],
                                          strCliente[4],
                                          strCliente[5],
                                          strCliente[6],
                                          Convert.ToInt32(strCliente[8]));
            client.update(cliente);

            if (!strCliente[7].Equals("0"))
            {
                //System.Windows.Forms.MessageBox.Show(strCliente[7]);
                modeloIndicado modInd = new modeloIndicado();
                modInd.insertOrUpdate(id, Convert.ToInt32(strCliente[7]));
            }

            DataRow[] srw = grid.dados.Select("[id_cliente] = " + id.ToString());
            DataRow dr = srw[0];
            dr["id_cliente"] = id.ToString();
            dr["nome"] = cliente.Nome;
            dr["telefone1"] = cliente.Telefone1;
            dr["telefone2"] = cliente.Telefone2;
            dr["email"] = cliente.Email;
            srw[0] = dr;
            HttpContext.Current.Session["GRID_CLINTE"] = grid;
            return "editou";
        }

        [WebMethod]
        public static string deleteFromTable(int id)
        {
            Grid grid = ((Grid)HttpContext.Current.Session["GRID_CLINTE"]);
            grid.deleteFromTable(id);
            modeloCliente client = new modeloCliente();
            client.delete(id);
            HttpContext.Current.Session["GRID_CLINTE"] = grid;
            return "removeu";
        }

        [WebMethod]
        public static string getClienteNome(string id)
        {
            modeloCliente mc = new modeloCliente();
            string ret = mc.getClientNome(id);
            return ret;
        }

        [WebMethod]
        public static string getDataFromClient(int id)
        {
            modeloCliente client = new modeloCliente();
            DataTable dt = client.getCliente(id);
            string retorno = "";

            client = new modeloCliente();
            DataTable dt2 = client.getClienteIndicator(id);

            if(dt.Rows.Count > 0)
            {
                retorno += dt.Rows[0]["nome"].ToString() + "|";
                retorno += Convert.ToDateTime(dt.Rows[0]["data_nascimento"]).ToString("dd/MM/yyyy") + "|";
                retorno += dt.Rows[0]["cpf"].ToString() + "|";
                retorno += dt.Rows[0]["rg"].ToString() + "|";
                retorno += dt.Rows[0]["telefone1"].ToString() + "|";
                retorno += dt.Rows[0]["telefone2"].ToString() + "|";
                retorno += dt.Rows[0]["email"].ToString() + "|";
                retorno += dt.Rows[0]["id_clinica"].ToString() + "#";

                retorno += dt.Rows[0]["rua"].ToString() + "|";
                retorno += dt.Rows[0]["numero"].ToString() + "|";
                retorno += dt.Rows[0]["cidade"].ToString() + "|";
                retorno += dt.Rows[0]["bairro"].ToString() + "|";
                retorno += dt.Rows[0]["uf"].ToString() + "|";
                retorno += dt.Rows[0]["cep"].ToString();

                if(dt2 != null && dt2.Rows.Count > 0)
                    retorno += "#"+dt2.Rows[0]["id_cliente_indicou"];

                HttpContext.Current.Session["ENDERECO_CLIENT"] = dt.Rows[0]["id_endereco"];
            }
            
            return retorno;
        }

        [WebMethod]
        public static void abreSaldo(int id, string nome)
        {
            HttpContext.Current.Session["id_cliente_logado"] = id;
            HttpContext.Current.Session["nome_cliente_logado"] = nome;
        }
    }
}